<template>
	<el-dialog @close="onCancel" :title="title" v-model="open" append-to-body :close-on-click-modal="false" width="90%">
		<el-form ref="formRef" :model="form" :rules="rules" label-width="110px">
			<el-tabs v-model="tabsName">
				<el-tab-pane label="基本信息" name="1">
					<el-row :gutter="10" class="mb20">
						<el-col :span="12">
							<el-form-item label="商品名" prop="title">
								<el-input v-model="form.title" placeholder="请输入商品名" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="商品分类" prop="goods_class_id">
								<el-cascader v-model="form.goods_class_id" :props="goodsClassProps" placeholder="请选择商品分类" class="w100" />
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="10" class="mb20">
						<el-col :span="12">
							<el-form-item label="商品标签" prop="tags_ids">
								<el-select v-model="form.tags_ids" multiple filterable placeholder="请选择商品标签" class="w100">
									<el-option v-for="item in goodsTagsOptions" :key="item.id" :label="item.name" :value="item.id" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="商品供应商" prop="supplier_name">
								<el-select
									v-model="form.supplier_name"
									filterable
									remote
									clearable
									placeholder="请输入选择供应商"
									:remote-method="supplierIdRemoteMethod"
									:loading="supplierIdLoading"
									@focus="onSupplierIdFocus"
									@clear="onSupplierIdClear"
									@change="onSupplierIdChange"
									class="w100"
								>
									<el-option v-for="item in supplierIdOptions" :key="item.id" :label="item.title" :value="item.title" />
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="10" class="mb20">
						<el-col :span="12">
							<el-form-item label="虚拟销量" prop="virtual_sales">
								<el-input-number v-model="form.virtual_sales" :min="0" :precision="0" :controls="false" placeholder="请输入虚拟销量" class="w100" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="排序" prop="display_order">
								<el-input-number v-model="form.display_order" :min="0" :precision="0" :controls="false" placeholder="请输入排序" class="w100" />
							</el-form-item>
						</el-col>
					</el-row>
					<!-- <el-row :gutter="10" class="mb20">
						<el-col :span="12">
							<el-form-item label="专区商品" prop="is_zone">
								<el-radio-group v-model="form.is_zone">
									<el-radio :label="0">否</el-radio>
									<el-radio :label="1">是</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
					</el-row> -->
					<el-row :gutter="10" class="mb20">
						<el-col>
							<el-form-item label="商品描述" prop="descri">
								<el-input v-model="form.descri" placeholder="请输入商品描述" />
							</el-form-item>
						</el-col>
					</el-row>
					<el-row class="mb20">
						<el-col :span="12">
							<el-form-item label="上架时间" prop="time">
								<el-date-picker
									v-model="form.time"
									type="datetimerange"
									start-placeholder="开始时间"
									end-placeholder="结束时间"
									format="YYYY/MM/DD HH:mm:ss"
									value-format="X"
									class="w100"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item prop="thumb_video">
								<template #label>
									商品视频<br />
									大小不超过5M
								</template>
								<image-upload-cOS v-model="form.thumb_video" video path="goods/thumb" ref="imageUploadThumbVideoRef" />
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="10" class="mb20">
						<el-col :span="12">
							<el-form-item prop="thumb">
								<template #label>
									商品封面图<br />
									宽高比例1:1<br />
									大小不超过2M
								</template>
								<image-upload-cOS v-model="form.thumb" path="goods/thumb" ref="imageUploadThumbRef" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item prop="share_img">
								<template #label>
									商品分享图<br />
									宽高比例5:4<br />
									大小不超过2M
								</template>
								<image-upload-cOS v-model="form.share_img" path="goods/indexShare" ref="imageUploadShareImgRef" />
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="10" class="mb20">
						<el-col>
							<el-form-item prop="images">
								<template #label>
									商品轮播图<br />
									宽高比例1:1<br />
									大小不超过2M
								</template>
								<image-upload-draggable-cOS v-model="form.images" :maxLength="4" path="goods/images" ref="imageUploadImagesRef" />
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="10" class="mb20">
						<el-col>
							<el-form-item prop="details">
								<template #label>
									商品详情图<br />
									宽750高1000以内<br />
									大小不超过2M
								</template>
								<image-upload-draggable-cOS v-model="form.details" :maxLength="30" path="goods/details" ref="imageUploadDetailsRef" />
							</el-form-item>
						</el-col>
					</el-row>
				</el-tab-pane>
				<el-tab-pane label="其他属性" name="2">
					<el-row :gutter="10">
						<el-col :span="21">
							<span style="color: red">
								注：<br />
								1.目前第一个规格可以设置不同的规格图片。设置后，用户选择不同规格会显示不同图片（建议尺寸：160 x 160像素）<br />
								2.修改规格时，数据需要从新录入
							</span>
						</el-col>
						<el-col :span="3">
							<el-button @click="onAddSpecs" plain icon="el-icon-plus"> 新增规格项目 </el-button>
						</el-col>
					</el-row>
					<el-table :data="specifications" border class="theme-2">
						<el-table-column label="规格名" width="130" align="center">
							<template #default="scope">
								<el-input v-model="scope.row.name" placeholder="请输入规格名" />
							</template>
						</el-table-column>
						<el-table-column label="规格值" align="center">
							<template #default="scope">
								<template v-if="scope.$index">
									<el-tag
										v-for="(item2, index2) in scope.row.leaf"
										:key="index2"
										closable
										size="medium"
										@close="onDeleteAttributeItem(scope.$index, index2)"
									>
										{{ item2.name }}
									</el-tag>
								</template>
								<template v-else>
									<div v-for="(item2, index2) in scope.row.leaf" :key="index2" class="img_sku-item">
										<el-tag closable size="medium" @close="onDeleteAttributeItem(scope.$index, index2)">{{ item2.name }} </el-tag>
										<div class="img_sku-item__upload">
											<el-icon
												v-if="item2.icon"
												@click.stop="onDeleteItemIcon(scope.$index, index2)"
												:size="15"
												color="#409eff"
												style="position: absolute; top: 0; right: 0; z-index: 10"
											>
												<i class="el-icon-close" />
											</el-icon>
											<div class="arrow" />
											<div class="upload-img">
												<el-upload
													action="#"
													:show-file-list="false"
													accept="image/jpeg,image/jpg,image/png"
													:on-error="onUploadError"
													:before-upload="beforeImagesUpload"
													:http-request="(response: any) => onUploadSuccess(response, scope.$index, index2)"
													class="img-uploader"
												>
													<el-image v-if="item2.icon" :src="item2.icon" fit="scale-down" />
													<i v-else class="el-icon-upload uploader-icon"></i>
												</el-upload>
											</div>
										</div>
									</div>
								</template>
							</template>
						</el-table-column>
						<el-table-column label="操作" align="center" width="300">
							<template #default="scope">
								<el-row :gutter="10">
									<el-col :span="18">
										<el-input v-model="scope.row.addAttribute" @keyup.enter="onAddAttribute(scope.$index)" placeholder="新增一个规格属性">
											<template #append>
												<el-button icon="el-icon-plus" @click="onAddAttribute(scope.$index)">添加</el-button>
											</template>
										</el-input>
									</el-col>
									<el-col :span="6">
										<el-button v-if="Number(scope.$index)" type="danger" @click="onDeleteAttribute(scope.$index)">删除 </el-button>
									</el-col>
								</el-row>
							</template>
						</el-table-column>
					</el-table>
					<el-table :data="specifications_val" border>
						<el-table-column label="规格属性" align="center">
							<template #default="scope">
								{{ scope.row.skus.map((item: any) => item.v).join('_') }}
							</template>
						</el-table-column>
						<el-table-column label="图片" align="center">
							<template #default="scope">
								<el-image v-if="scope.row.icon" :src="scope.row.icon" fit="scale-down" style="width: 50px; height: 50px" />
							</template>
						</el-table-column>
						<el-table-column align="center">
							<template #header>
								<span class="required_title"> 库存 </span>
								<el-button type="info" @click="onBatchSet('stock')">同步</el-button>
							</template>
							<template #default="scope">
								<el-input-number
									v-model="scope.row.stock"
									:min="0"
									:precision="0"
									:controls="false"
									:disabled="disabledStock"
									placeholder="请输入库存"
								/>
							</template>
						</el-table-column>
						<el-table-column label="原价" align="center">
							<template #header>
								<span class="required_title"> 原价 </span>
								<el-button type="info" @click="onBatchSet('old_price')">同步</el-button>
							</template>
							<template #default="scope">
								<el-input-number v-model="scope.row.old_price" :min="0" :precision="2" :controls="false" placeholder="请输入原价" />
							</template>
						</el-table-column>
						<el-table-column align="center">
							<template #header>
								<span class="required_title"> 成本价 </span>
								<el-button type="info" @click="onBatchSet('cost_price')">同步</el-button>
							</template>
							<template #default="scope">
								<el-input-number v-model="scope.row.cost_price" :min="0" :precision="2" :controls="false" placeholder="请输入成本价" />
							</template>
						</el-table-column>
						<el-table-column align="center">
							<template #header>
								<span class="required_title"> 管家佣金 </span>
								<el-button type="info" @click="onBatchSet('sale_price_member')">同步</el-button>
							</template>
							<template #default="scope">
								<el-input-number v-model="scope.row.sale_price_member" :min="0" :precision="2" :controls="false" placeholder="请输入会员价" />
							</template>
						</el-table-column>
						<el-table-column align="center">
							<template #header>
								<span class="required_title"> 经理佣金 </span>
								<el-button type="info" @click="onBatchSet('sale_price_member1')">同步</el-button>
							</template>
							<template #default="scope">
								<el-input-number v-model="scope.row.sale_price_member1" :min="0" :precision="2" :controls="false" placeholder="请输入会员价" />
							</template>
						</el-table-column>
						<el-table-column align="center">
							<template #header>
								<span class="required_title"> 平台服务费 </span>
								<el-button type="info" @click="onBatchSet('service_price')">同步</el-button>
							</template>
							<template #default="scope">
								<el-input-number v-model="scope.row.service_price" :min="0" :precision="2" :controls="false"
									placeholder="请输入平台服务费" />
							</template>
						</el-table-column>
						<el-table-column align="center">
							<template #header>
								售价
								<el-tooltip effect="dark" content="售价 = 成本价 + 管家佣金 + 公司佣金 + 平台服务费" placement="top">
									<i class="el-icon-info" />
								</el-tooltip>
							</template>
							<template #default="scope">
								{{ totalPrice(scope.row) }}
							</template>
						</el-table-column>
					</el-table>
					<el-row :gutter="10" class="mt20">
						<el-col :span="12">
							<el-form-item label="不支持包邮区域">
								<el-row :gutter="10" class="mb10">
									<el-col :span="17">
										<el-cascader v-model="shippingInfo.area" :props="shippingProvinceProps" placeholder="请选择省市区" class="w100" />
									</el-col>
									<el-col :span="4">
										<el-input-number v-model="shippingInfo.price" :min="0" :precision="1" :controls="false" placeholder="输入运费" class="w100" />
									</el-col>
									<el-col :span="2">
										<el-button @click="onAddShipping" type="primary"> 添加 </el-button>
									</el-col>
								</el-row>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="不支持配送区域">
								<el-row :gutter="10">
									<el-col :span="20">
										<el-cascader v-model="deliveryInfo.area" :props="deliveryProvinceProps" placeholder="请选择省市区" class="w100" />
									</el-col>
									<el-col :span="2">
										<el-button @click="onAddDelivery" type="primary"> 添加 </el-button>
									</el-col>
								</el-row>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row :gutter="10" class="mt20">
						<el-col :span="12">
							<el-table :data="form.shipping" border>
								<el-table-column label="省/市/区、县" align="center">
									<template #default="scope">
										{{ scope.row.combination.join('-') }}
									</template>
								</el-table-column>
								<el-table-column label="运费(元)" align="center" prop="price" />
								<el-table-column label="操作" width="100" align="center">
									<template #default="scope">
										<el-button @click="onDeleteShipping(scope.$index)" type="danger" plain> 删除 </el-button>
									</template>
								</el-table-column>
							</el-table>
						</el-col>
						<el-col :span="12">
							<el-table :data="form.delivery" border>
								<el-table-column label="省/市" align="center">
									<template #default="scope">
										{{ scope.row.combination.join('-') }}
									</template>
								</el-table-column>
								<el-table-column label="操作" width="100" align="center">
									<template #default="scope">
										<el-button @click="onDeleteDelivery(scope.$index)" type="danger" plain> 删除 </el-button>
									</template>
								</el-table-column>
							</el-table>
						</el-col>
					</el-row>
					<el-row :gutter="10" class="mt20">
						<el-col :span="4">
							<el-input v-model="receivingAddressInfo.name" placeholder="收货联系人" />
						</el-col>
						<el-col :span="4">
							<el-input v-model="receivingAddressInfo.mobile" placeholder="收货手机号" />
						</el-col>
						<el-col :span="14">
							<el-cascader v-model="receivingAddressInfo.area" :props="receivingAddressProps" placeholder="请选择省市区" class="w100" />
						</el-col>
						<el-col :span="2">
							<el-button @click="onAddReceivingAddress" type="primary"> 添加地址 </el-button>
						</el-col>
					</el-row>
					<el-row :gutter="10" class="mt20">
						<el-col :span="24">
							<el-input type="textarea" :rows="3" placeholder="详细地址" v-model="receivingAddressInfo.address" />
						</el-col>
					</el-row>
					<el-row :gutter="10" class="mt20">
						<el-col :span="24">
							<span style="color: red"> 注：至少添加一个退换货地址，便于用户申请售后 </span>
						</el-col>
					</el-row>
					<el-row :gutter="10" class="mt20">
						<el-col>
							<el-form-item label="退换货地址">
								<el-table :data="form.receiving_address" border>
									<el-table-column label="地址" align="center">
										<template #default="scope">
											{{ receivingAddressFilters(scope.row) }}
										</template>
									</el-table-column>
									<el-table-column label="操作" width="100" align="center">
										<template #default="scope">
											<el-button type="danger" plain @click="onDeleteAddress(scope.$index)"> 删除 </el-button>
										</template>
									</el-table-column>
								</el-table>
							</el-form-item>
						</el-col>
					</el-row>
				</el-tab-pane>
			</el-tabs>
		</el-form>
		<template #footer>
			<div class="dialog-footer">
				<el-button type="primary" :loading="submitLoading" @click="onProcedure"> {{ tabsName === '1' ? '下一步' : '上一步' }} </el-button>
				<el-button v-if="tabsName === '2'" type="primary" :loading="submitLoading" @click="onSubmitForm"> 确 定 </el-button>
				<el-button @click="onCancel">取 消</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script lang="ts">
import { getCurrentInstance, nextTick, reactive, ref, toRefs } from 'vue';
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus';
import { getAreaList } from '/@/api/admin';
import { goodsSelectClass, goodsSelectSupplier, goodsTagsList, goodsSelect, goodsEdit, goodsEditSku } from '/@/api/admin1';
import { Session } from '/@/utils/storage';
import uploadCos from '/@/utils/uploadCos';
import { randomString } from '/@/utils/utils';

export default {
	name: 'goodEditDialog',
	setup() {
		const state = reactive({
			title: '商品修改',
			open: false,
			tabsName: '1',
			headers: {
				token: Session.get('token'),
			},
			form: {} as any,
			rules: {
				title: [{ required: true, message: '商品名不能为空', trigger: ['blur'] }],
				time: [{ required: true, message: '上架时间不能为空', trigger: ['blur', 'change'] }],
				goods_class_id: [{ required: true, message: '商品分类不能为空', trigger: ['blur', 'change'] }],
				tags_ids: [{ required: true, message: '商品标签不能为空', trigger: ['blur', 'change'] }],
				supplier_name: [{ required: true, message: '商品供应商不能为空', trigger: ['blur', 'change'] }],
				virtual_sales: [{ required: true, message: '虚拟销量不能为空', trigger: ['blur'] }],
				// proportion: [{ required: true, message: '分佣比例不能为空', trigger: ['blur'] }],
				display_order: [{ required: true, message: '排序不能为空', trigger: ['blur'] }],
				descri: [{ required: true, message: '商品描述不能为空', trigger: ['blur'] }],
				thumb: [{ required: true, message: '商品封面图不能为空', trigger: ['blur', 'change'] }],
				share_img: [{ required: true, message: '商品分享图不能为空', trigger: ['blur', 'change'] }],
				images: [{ required: true, message: '商品轮播图不能为空', trigger: ['blur', 'change'] }],
				details: [{ required: true, message: '商品详情不能为空', trigger: ['blur', 'change'] }],
			}, // 表单校验
			goodsClassProps: {
				lazy: true,
				lazyLoad(node: any, resolve: any) {
					const { value, level } = node;
					_goodsSelectClass({ pid: level ? value : 0, pageNum: 1, pageSize: 100 }, level, resolve);
				},
				value: 'id',
				label: 'name',
			},
			shippingProvinceProps: {
				checkStrictly: true,
				lazy: true,
				lazyLoad(node: any, resolve: any) {
					const {
						data: { id },
						level,
					} = node;
					_getAreaList({ id: level ? id : 100000 }, level, resolve);
				},
				value: 'name',
				label: 'name',
			},
			deliveryProvinceProps: {
				checkStrictly: true,
				lazy: true,
				lazyLoad(node: any, resolve: any) {
					const {
						data: { id },
						level,
					} = node;
					_getAreaList({ id: level ? id : 100000 }, level, resolve);
				},
				value: 'name',
				label: 'name',
			},
			receivingAddressProps: {
				lazy: true,
				lazyLoad(node: any, resolve: any) {
					const {
						data: { id },
						level,
					} = node;
					_getAreaList({ id: level ? id : 100000 }, level, resolve);
				},
				value: 'name',
				label: 'name',
			},
			goodsTagsOptions: [] as any,
			supplierIdLoading: false,
			supplierIdOptions: [] as any,
			shippingInfo: {
				area: [],
				price: 0,
			},
			deliveryInfo: {
				area: '',
			},
			remoteLoading: false,
			submitLoading: false,
			specifications: [
				{
					id: '1',
					addAttribute: '',
					name: '',
					leaf: [] as any,
				},
			],
			specifications_val: [] as any,
			receivingAddressInfo: {
				name: '',
				mobile: '',
				area: [],
				address: '',
			},
			disabledStock: true,
		});

		const formRef = ref(null);
		const imageUploadThumbVideoRef = ref(null);
		const imageUploadThumbRef = ref(null);
		const imageUploadShareImgRef = ref(null);
		const imageUploadImagesRef = ref(null);
		const imageUploadDetailsRef = ref(null);
		const loadingUploadRef = ref(null);
		const { proxy } = getCurrentInstance() as any;
		let callback: Function = () => {};

		/********** computed **********/
		/********** 点击事件(on开头) **********/
		// 选择供应商
		const onSupplierIdFocus = () => {
			if (!state.form.supplier_name) {
				state.supplierIdLoading = true;
				_goodsSelectSupplier();
			}
		};
		// 清空供应商
		const onSupplierIdClear = () => {
			_goodsSelectSupplier();
		};
		// 选中供应商
		const onSupplierIdChange = (val: any) => {
			const supplierIdData = state.supplierIdOptions.find((item: any) => item.title == val);
			state.form.supplier_id = supplierIdData.id;
			state.form.supplier_name = supplierIdData.title;
		};
		// 新增SKU
		const onAddSpecs = () => {
			if (!state.specifications[state.specifications.length - 1].name || !state.specifications[state.specifications.length - 1].leaf.length) {
				ElMessage.warning('请完善已有规格');
				return true;
			}
			state.disabledStock = false;
			state.specifications.push({
				id: String(Number(state.specifications[state.specifications.length - 1].id) + 1),
				addAttribute: '',
				name: '',
				leaf: [],
			});
		};
		// 删除SKU某项属性
		const onDeleteAttributeItem = (index1: number, index2: number) => {
			if (state.specifications[index1].leaf.length < 2) {
				ElMessage.warning('至少保留一个属性');
				return true;
			}
			state.disabledStock = false;
			state.specifications[index1].leaf.splice(index2, 1);
			combinationAttribute();
		};
		// 删除规格图片
		const onDeleteItemIcon = (index: number, index2: number) => {
			state.specifications[index].leaf[index2].icon = '';
			state.specifications_val = state.specifications_val.map((item: any) => {
				return {
					...item,
					icon: state.specifications[index].leaf[index2].id == item.skus[0].v_id ? '' : item.icon,
				};
			});
		};
		// 上传图片
		const onUploadSuccess = (fileRes: any, index: number, index2: number) => {
			let fileExtension = fileRes.file.name.substring(fileRes.file.name.lastIndexOf('.') + 1);
			let path = `/hbsk_cloud/gooods/specsIcon/${proxy.dayjs().year()}/${proxy.dayjs().month()}/${proxy.dayjs().date()}/${randomString(
				32
			).toLowerCase()}.${fileExtension}`;
			uploadCos(fileRes.file, path)
				.then((res: any) => {
					state.specifications[index].leaf[index2].icon = res.url;
					state.specifications_val = state.specifications_val.map((item: any) => {
						return {
							...item,
							icon: state.specifications[index].leaf[index2].id == item.skus[0].v_id ? res.url : item.icon,
						};
					});
					(loadingUploadRef.value as any)?.close();
				})
				.catch(() => {
					(loadingUploadRef.value as any)?.close();
				});
		};
		const onUploadError = () => {
			ElMessage.error('上传失败');
			(loadingUploadRef.value as any)?.close();
		};
		// 上传图片校验
		const beforeImagesUpload = (file: any) => {
			let types = ['image/jpeg', 'image/png', 'image/jpg'];
			const isJPG = types.includes(file.type);
			const isLt2M = file.size / 1024 / 1024 < 1;
			if (!isJPG) {
				ElMessage.warning('只能是 jpeg,png,jpg 格式');
				return isJPG;
			}
			if (!isLt2M) {
				ElMessage.warning('上传图片大小不能超过 1M');
				return isLt2M;
			}
			(loadingUploadRef.value as any) = ElLoading.service({
				lock: true,
				text: '上传中',
				background: 'rgba(0, 0, 0, 0.7)',
			});
		};
		// 新增SKU属性
		const onAddAttribute = (index: number) => {
			if (!state.specifications[index].name) {
				ElMessage.warning('请输入规格名');
				return true;
			}
			state.specifications[index].addAttribute = state.specifications[index].addAttribute.trim();
			if (state.specifications[index].addAttribute) {
				if (!state.specifications[index].addAttribute.includes('_')) {
					let leaf = state.specifications[index].leaf.filter((item: any) => item.name == state.specifications[index].addAttribute);
					if (!leaf.length) {
						if (state.specifications[index].leaf.length) {
							state.specifications[index].leaf.push({
								id: String(Number(state.specifications[index].leaf[state.specifications[index].leaf.length - 1].id) + 1),
								name: state.specifications[index].addAttribute,
								icon: '',
							});
						} else {
							state.specifications[index].leaf.push({
								id: state.specifications[index].id + '1',
								name: state.specifications[index].addAttribute,
								icon: '',
							});
						}
					} else {
						ElMessage.warning('规格里不允许出现相同的规格值');
					}
				} else {
					ElMessage.warning('规格里不允许出现「 _ 」字符，请检查后重新添加');
				}
			}
			combinationAttribute();
		};
		// 删除SKU
		const onDeleteAttribute = (index: number) => {
			state.specifications.splice(index, 1);
			combinationAttribute();
		};
		//批量设置
		const onBatchSet = (type: string) => {
			state.specifications_val = state.specifications_val.map((item: any) => {
				return {
					...item,
					stock: type == 'stock' ? state.specifications_val[0].stock : item.stock,
					old_price: type == 'old_price' ? state.specifications_val[0].old_price : item.old_price,
					cost_price: type == 'cost_price' ? state.specifications_val[0].cost_price : item.cost_price,
					sale_price_member: type == 'sale_price_member' ? state.specifications_val[0].sale_price_member : item.sale_price_member,
					sale_price_member1: type == 'sale_price_member1' ? state.specifications_val[0].sale_price_member1 : item.sale_price_member1,
					service_price: type == 'service_price' ? state.specifications_val[0].service_price : item.service_price,
				};
			});
		};
		// 不支持包邮区域
		const onAddShipping = () => {
			let areaArray = state.shippingInfo.area;
			if (!areaArray.length) {
				ElMessage.warning('请选择不支持包邮区域');
				return true;
			}
			if (!state.shippingInfo.price) {
				ElMessage.warning('请输入运费');
				return true;
			}
			if (areaArray.length == 3) {
				let isarea = state.form.shipping.findIndex((item: any) => {
					return item.county == areaArray[2];
				});
				let iscity = state.form.shipping.findIndex((item: any) => {
					return !item.county && item.city == areaArray[1];
				});
				let isprovince = state.form.shipping.findIndex((item: any) => {
					return !item.county && !item.city && item.province == areaArray[0];
				});
				if (isarea > -1) {
					ElMessage.warning('该区、县已被添加');
					return true;
				}
				if (iscity > -1) {
					ElMessage.warning('该区、县已被城市包含');
					return true;
				}
				if (isprovince > -1) {
					ElMessage.warning('该区、县已被省份包含');
					return true;
				}
			} else if (areaArray.length == 2) {
				let isarea = state.form.shipping.findIndex((item: any) => {
					return item.county && item.city == areaArray[1];
				});
				let iscity = state.form.shipping.findIndex((item: any) => {
					return !item.county && item.city == areaArray[1];
				});
				let isprovince = state.form.shipping.findIndex((item: any) => {
					return !item.city && item.province == areaArray[0];
				});
				if (isarea > -1) {
					ElMessage.warning('该城市已添加了部分区、县');
					return true;
				}
				if (iscity > -1) {
					ElMessage.warning('该城市已被添加');
					return true;
				}
				if (isprovince > -1) {
					ElMessage.warning('该城市已被省份包含');
					return true;
				}
			} else {
				let isarea = state.form.shipping.findIndex((item: any) => {
					return item.county && item.city && item.province == areaArray[0];
				});
				let iscity = state.form.shipping.findIndex((item: any) => {
					return item.city && item.province == areaArray[0];
				});
				let isprovince = state.form.shipping.findIndex((item: any) => {
					return item.province == areaArray[0];
				});
				if (isarea > -1) {
					ElMessage.warning('该省份已添加了部分区、县');
					return true;
				}
				if (iscity > -1) {
					ElMessage.warning('该省份已添加了部分城市');
					return true;
				}
				if (isprovince > -1) {
					ElMessage.warning('该省份已被添加');
					return true;
				}
			}
			state.form.shipping.push({
				combination: areaArray,
				province: areaArray[0],
				city: areaArray.length > 1 ? areaArray[1] : '',
				county: areaArray.length > 2 ? areaArray[2] : '',
				price: state.shippingInfo.price,
			});
		};
		// 不支持配送区域
		const onAddDelivery = () => {
			let areaArray = state.deliveryInfo.area;
			if (!areaArray.length) {
				ElMessage.warning('请选择不支持包邮区域');
				return true;
			}
			if (areaArray.length == 3) {
				let isarea = state.form.delivery.findIndex((item: any) => {
					return item.county == areaArray[2];
				});
				let iscity = state.form.delivery.findIndex((item: any) => {
					return !item.county && item.city == areaArray[1];
				});
				let isprovince = state.form.delivery.findIndex((item: any) => {
					return !item.county && !item.city && item.province == areaArray[0];
				});
				if (isarea > -1) {
					ElMessage.warning('该区、县已被添加');
					return true;
				}
				if (iscity > -1) {
					ElMessage.warning('该区、县已被城市包含');
					return true;
				}
				if (isprovince > -1) {
					ElMessage.warning('该区、县已被省份包含');
					return true;
				}
			} else if (areaArray.length == 2) {
				let isarea = state.form.delivery.findIndex((item: any) => {
					return item.county && item.city == areaArray[1];
				});
				let iscity = state.form.delivery.findIndex((item: any) => {
					return !item.county && item.city == areaArray[1];
				});
				let isprovince = state.form.delivery.findIndex((item: any) => {
					return !item.city && item.province == areaArray[0];
				});
				if (isarea > -1) {
					ElMessage.warning('该城市已添加了部分区、县');
					return true;
				}
				if (iscity > -1) {
					ElMessage.warning('该城市已被添加');
					return true;
				}
				if (isprovince > -1) {
					ElMessage.warning('该城市已被省份包含');
					return true;
				}
			} else {
				let isarea = state.form.delivery.findIndex((item: any) => {
					return item.county && item.city && item.province == areaArray[0];
				});
				let iscity = state.form.delivery.findIndex((item: any) => {
					return item.city && item.province == areaArray[0];
				});
				let isprovince = state.form.delivery.findIndex((item: any) => {
					return item.province == areaArray[0];
				});
				if (isarea > -1) {
					ElMessage.warning('该省份已添加了部分区、县');
					return true;
				}
				if (iscity > -1) {
					ElMessage.warning('该省份已添加了部分城市');
					return true;
				}
				if (isprovince > -1) {
					ElMessage.warning('该省份已被添加');
					return true;
				}
			}
			state.form.delivery.push({
				combination: areaArray,
				province: areaArray[0],
				city: areaArray.length > 1 ? areaArray[1] : '',
				county: areaArray.length > 2 ? areaArray[2] : '',
			});
		};
		// 不支持包邮区域删除
		const onDeleteShipping = (_index: number) => {
			ElMessageBox.confirm('此操作将删除该配置, 是否继续?', '提示', {
				confirmButtonText: '删除',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				ElMessage.success('删除成功');
				state.form.shipping.splice(_index, 1);
			});
		};
		// 不支持配送区域删除
		const onDeleteDelivery = (_index: number) => {
			ElMessageBox.confirm('此操作将删除该配置, 是否继续?', '提示', {
				confirmButtonText: '删除',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				ElMessage.success('删除成功');
				state.form.delivery.splice(_index, 1);
			});
		};
		// 退货地址
		const onAddReceivingAddress = () => {
			if (!state.receivingAddressInfo.name) {
				ElMessage.warning('请输入收货人');
				return true;
			}
			if (state.receivingAddressInfo.mobile.length < 11) {
				ElMessage.warning('请输入11位以上的联系方式');
				return true;
			}
			if (!state.receivingAddressInfo.area.length) {
				ElMessage.warning('请选择省市区');
				return true;
			}
			if (!state.receivingAddressInfo.address) {
				ElMessage.warning('请输入详细地址');
				return true;
			}
			state.form.receiving_address.push({
				name: state.receivingAddressInfo.name,
				mobile: state.receivingAddressInfo.mobile,
				province: state.receivingAddressInfo.area[0],
				city: state.receivingAddressInfo.area[1],
				county: state.receivingAddressInfo.area[2],
				address: state.receivingAddressInfo.address,
			});
		};
		//删除退货地址
		const onDeleteAddress = (index: number) => {
			state.form.receiving_address.splice(index, 1);
		};
		// 步骤
		const onProcedure = () => {
			state.tabsName = state.tabsName === '1' ? '2' : '1';
		};
		/** 提交按钮 */
		const onSubmitForm = () => {
			(formRef.value as any)?.validate((valid: boolean) => {
				if (valid) {
					if (!state.specifications_val.length) {
						ElMessage.warning('请完善其他属性');
						return true;
					}
					// const iconIndex = state.specifications_val.findIndex((item: any) => !item.icon);
					const oldPriceIndex = state.specifications_val.findIndex((item: any) => !item.old_price);
					const costPriceIndex = state.specifications_val.findIndex((item: any) => !item.cost_price);
					// if (iconIndex > -1) {
					// 	ElMessage.warning('请完善规格图片');
					// 	return true;
					// }
					if (oldPriceIndex > -1) {
						ElMessage.warning('规格中的「原价」不能为0');
						return true;
					}
					if (costPriceIndex > -1) {
						ElMessage.warning('规格中的「成本」价不能为0');
						return true;
					}
					let specifications = state.specifications.map((item: any, index: number) => {
						let leaf = item.leaf.map((leaf_item: any) => {
							return {
								...leaf_item,
								icon: index
									? ''
									: leaf_item.icon
									? leaf_item.icon.replace(import.meta.env.VITE_FILE_API, '')
									: state.form.thumb.replace(import.meta.env.VITE_FILE_API, ''),
							};
						});
						return {
							...item,
							leaf,
						};
					});
					let specifications_val = state.specifications_val.map((item: any) => {
						return {
							...item,
							sale_price: totalPrice(item),
							icon: item.icon ? item.icon.replace(import.meta.env.VITE_FILE_API, '') : state.form.thumb.replace(import.meta.env.VITE_FILE_API, ''),
						};
					});
					if (specifications_val.findIndex((item: any) => item.sale_price > item.old_price) > -1) {
						ElMessage.warning('规格售价不能大于原价');
						return true;
					}
					let goodsSpecsItem: Array<any> = specifications.map((item: any) => {
						let leaf_str = item.leaf.map((item1: any) => item1.id).join(',');
						return leaf_str;
					});
					const goods_specs_str = specifications.map((item: any) => item.id).join(',');
					const goods_specs_item_str = goodsSpecsItem.map((item: any) => item).join(',');
					const goods_option_str = specifications_val.map((item: any) => item.id).join(',');
					let _images = state.form.images.split(',').map((item: any) => ({ url: item.replace(import.meta.env.VITE_FILE_API, '') }));
					let _details = state.form.details.split(',').map((item: any) => ({ url: item.replace(import.meta.env.VITE_FILE_API, ''), url_show: item }));
					let params = {
						display_order: state.form.display_order,
						goods_id: state.form.goods_id,
						supplier_id: state.form.supplier_id,
						title: state.form.title,
						is_zone: state.form.is_zone,
						descri: state.form.descri,
						details: JSON.stringify(_details),
						virtual_sales: state.form.virtual_sales,
						thumb: state.form.thumb.replace(import.meta.env.VITE_FILE_API, ''),
						share_img: state.form.share_img.replace(import.meta.env.VITE_FILE_API, ''),
						images: JSON.stringify(_images),
						shipping: state.form.shipping,
						delivery: state.form.delivery,
						goods_class_id: state.form.goods_class_id[1],
						tags_ids: state.form.tags_ids.join(','),
						goods_sn: '',
						thumb_video: state.form.thumb_video.replace(import.meta.env.VITE_FILE_API, ''),
						receiving_address: JSON.stringify(state.form.receiving_address),
						start_time: state.form.time[0],
						end_time: state.form.time[1],
					};
					let params1 = {
						goods_id: state.form.goods_id,
						specifications: JSON.stringify({ specifications, specifications_val }),
						goods_specs_item_str,
						goods_specs_str,
						goods_option_str,
					};
					_goodsEdit(params, params1);
				} else {
					ElMessage.warning('请完善基本信息或其他属性');
				}
			});
		};
		// 取消按钮
		const onCancel = () => {
			state.submitLoading = false;
			state.open = false;
			reset();
		};

		/********** 方法事件 **********/
		//打开
		const openDialog = (config: any, fn: Function) => {
			console.log(config);
			callback = fn;
			state.open = true;
			reset();
			_goodsSelect(config.data);
			_goodsTagsList({ pageNum: 1, pageSize: 100 });
			_goodsSelectSupplier();
		};
		// 表单重置
		const reset = () => {
			state.tabsName = '1';
			state.form = {
				display_order: 0, // 排序
				goods_class_id: '', // 商品分类
				supplier_id: '', // 供应商id
				supplier_name: '', // 供应商
				time: [1672502400, 1988121600],
				thumb_video: '', // 商品视频
				is_zone: 0, // 是否采集商品
				title: '', // 商品名
				descri: '', // 描述
				thumb: '', // 封面图
				// proportion: 70, // 分佣比例
				images: '', // 轮播图
				details: '', // 商品详情
				tags_ids: [], // 标签
				shipping: [], // 不包邮
				delivery: [], // 不配送
				virtual_sales: 0, // 虚拟销量
				share_img: '', // 分享图
				specifications: '', // 规格属性sku
				receiving_address: [], // 退货地址
				goods_id: '', // 商品id
			};
			state.specifications = [
				{
					id: '1',
					addAttribute: '',
					name: '',
					leaf: [],
				},
			];
			state.specifications_val = [];
			state.receivingAddressInfo = {
				name: '',
				mobile: '',
				area: [],
				address: '',
			};
			(formRef.value as any)?.resetFields();
			nextTick(() => {
				(imageUploadThumbVideoRef.value as any)?.reset();
				(imageUploadThumbRef.value as any)?.reset();
				(imageUploadShareImgRef.value as any)?.reset();
				(imageUploadImagesRef.value as any)?.reset();
				(imageUploadDetailsRef.value as any)?.reset();
			});
		};
		// 生成 skuData 数据
		const combinationAttribute = () => {
			let specifications = state.specifications.map((item: any) => {
				return item.leaf.map((item1: any) => item1.name);
			});
			let specifications_val = calcDescartes(specifications).map((item: any) => {
				let skus: any = [];
				let icon = '';
				state.specifications.map((item1: any, index: number) => {
					item1.leaf.map((item2: any) => {
						if (item2.name === item[index]) {
							skus.push({
								k: item1.name,
								k_id: item1.id,
								v: item2.name,
								v_id: item2.id,
							});
						}
					});
				});
				state.specifications[0].leaf.map((item1: any) => {
					if (item1.name == item[0]) {
						icon = item1.icon;
					}
				});
				return {
					stock: 0,
					old_price: 0,
					cost_price: 0,
					sale_price: 0,
					sale_price_member: 0,
					sale_price_member1: 0,
					service_price: 0,
					skus: skus,
					icon,
				};
			});
			state.specifications_val = specifications_val;
		};
		// 生成sku
		const calcDescartes = (array: any) => {
			if (array.length < 2) return array[0].map((item: any) => [item]) || [];
			return Array.prototype.reduce.call(
				array,
				(col: any, set: any) => {
					var res: any = [];
					col.forEach((c: any) => {
						set.forEach((s: any) => {
							res.push(c.concat([s]));
						});
					});
					return res;
				},
				[[]]
			);
		};
		// 退货地址组合
		const receivingAddressFilters = (row: any) => {
			return `${row.name},${row.mobile},${row.province},${row.city},${row.county},${row.address}`;
		};
		//搜索供应商
		const supplierIdRemoteMethod = (query: string) => {
			if (query) {
				state.supplierIdLoading = true;
				_goodsSelectSupplier({ title: query });
			} else {
				return true;
			}
		};
		const totalPrice = (row: any) => {
			let cost_price = Number(row.cost_price) * 1000;
			let sale_price_member = Number(row.sale_price_member) * 1000;
			let sale_price_member1 = Number(row.sale_price_member1) * 1000;
			let service_price = Number(row.service_price) * 1000;
			return (cost_price + sale_price_member + sale_price_member1 + service_price) / 1000;
		};

		/********** 网络事件 **********/
		// 选择商品分类
		const _goodsSelectClass = (_data: object, _level: number, resolve: any) => {
			goodsSelectClass(_data).then((res: any) => {
				let nodes = res.data.list.map((item: any) => ({
					id: item.id,
					name: item.name,
					leaf: _level >= 1,
				}));
				resolve(nodes);
			});
		};
		// 选择供应商
		const _goodsSelectSupplier = (_data: object = {}) => {
			goodsSelectSupplier(_data)
				.then((res: any) => {
					console.log('选择供应商', res);
					state.supplierIdOptions = res.data.list;
					state.supplierIdLoading = false;
				})
				.catch(() => {
					state.supplierIdLoading = false;
				});
		};
		// 选择标签
		const _goodsTagsList = (_data: object) => {
			goodsTagsList(_data).then((res: any) => {
				console.log('选择标签', res);
				state.goodsTagsOptions = res.data.list;
			});
		};
		// 选择省市区
		const _getAreaList = (_data: object, _level: number, resolve: any) => {
			getAreaList(_data).then((res: any) => {
				console.log('选择省市区', res);
				let nodes = res.data.list.map((item: any) => ({
					id: item.id,
					name: item.name,
					leaf: _level >= 2,
				}));
				resolve(nodes);
			});
		};
		// 商品查询
		const _goodsSelect = (_data: object) => {
			goodsSelect(_data).then((res: any) => {
				let info: any = res.data.info;
				let images = info.images.map((item: any) => item.url_show).join(',');
				let tags_ids = info.tags.map((item: any) => item.id);
				let details = JSON.parse(info.details)
					.map((item: any) => item.url_show)
					.join(',');
				let shipping = info.goods_not_mail.map((item: any) => {
					let combination = [];
					if (item.county) {
						combination = [item.province, item.city, item.county];
					} else if (item.city) {
						combination = [item.province, item.city];
					} else {
						combination = [item.province];
					}
					return {
						combination,
						province: item.province,
						city: item.city,
						county: item.county,
						price: item.price,
					};
				});
				let delivery = info.goods_not_send.map((item: any) => {
					let combination = [];
					if (item.county) {
						combination = [item.province, item.city, item.county];
					} else if (item.city) {
						combination = [item.province, item.city];
					} else {
						combination = [item.province];
					}
					return {
						combination,
						province: item.province,
						city: item.city,
						county: item.county,
					};
				});
				state.specifications = res.data.specifications.specifications.map((item: any) => {
					let leaf = item.leaf.map((leaf_item: any) => {
						return {
							id: leaf_item.id,
							name: leaf_item.name,
							icon: leaf_item.icon_show,
						};
					});
					return {
						id: item.id,
						name: item.name,
						leaf: leaf,
						addAttribute: '',
					};
				});
				state.specifications_val = res.data.specifications.specifications_val.map((item: any) => {
					return {
						id: item.id,
						stock: Number(item.stock),
						old_price: Number(item.old_price),
						cost_price: Number(item.cost_price),
						sale_price: Number(item.sale_price),
						sale_price_member: Number(item.sale_price_member),
						sale_price_member1: Number(item.sale_price_member1),
						service_price: Number(item.service_price),
						icon: item.icon_show,
						skus: item.skus,
					};
				});

				state.form = {
					...state.form,
					display_order: info.display_order,
					goods_class_id: [info.goods_class_pid, info.goods_class_id],
					supplier_id: info.supplier_id,
					supplier_name: info.supplier_name,
					title: info.title,
					descri: info.descri,
					is_zone: info.is_zone,
					thumb: info.thumb_show,
					images: images,
					details: details,
					tags_ids: tags_ids,
					shipping: shipping,
					delivery: delivery,
					virtual_sales: info.virtual_sales,
					share_img: info.share_img_show,
					receiving_address: info.goods_receiving_address,
					thumb_video: info.thumb_video_show,
					time: [info.start_time, info.end_time],
					goods_id: info.id,
				};
				console.log(state.form);
				nextTick(() => {
					(imageUploadThumbVideoRef.value as any)?.dataLoading();
					(imageUploadThumbRef.value as any)?.dataLoading();
					(imageUploadShareImgRef.value as any)?.dataLoading();
					(imageUploadImagesRef.value as any)?.dataLoading();
					(imageUploadDetailsRef.value as any)?.dataLoading();
				});
			});
		};
		// 编辑商品 - 基础信息
		const _goodsEdit = (_data: object, _data1: object) => {
			goodsEdit(_data)
				.then((res: any) => {
					console.log('编辑商品 - 基础信息', res);
					_goodsEditSku(_data1);
				})
				.catch(() => {
					state.submitLoading = false;
				});
		};
		// 编辑商品 - sku
		const _goodsEditSku = (_data: object) => {
			goodsEditSku(_data)
				.then((res: any) => {
					console.log('编辑商品 - sku', res);
					ElMessage.success('修改成功');
					onCancel();
					callback();
				})
				.catch(() => (state.submitLoading = false));
		};

		return {
			formRef,
			imageUploadThumbVideoRef,
			imageUploadThumbRef,
			imageUploadShareImgRef,
			imageUploadImagesRef,
			imageUploadDetailsRef,
			onSupplierIdFocus,
			onSupplierIdClear,
			onSupplierIdChange,
			onAddSpecs,
			onDeleteAttributeItem,
			onDeleteItemIcon,
			onUploadSuccess,
			onUploadError,
			beforeImagesUpload,
			onAddAttribute,
			onDeleteAttribute,
			onBatchSet,
			onAddShipping,
			onAddDelivery,
			onDeleteShipping,
			onDeleteDelivery,
			onAddReceivingAddress,
			onDeleteAddress,
			onProcedure,
			onSubmitForm,
			openDialog,
			onCancel,
			totalPrice,
			receivingAddressFilters,
			supplierIdRemoteMethod,
			...toRefs(state),
		};
	},
};
</script>

<style lang="scss" scoped>
.theme-2 {
	border: 1px solid #ebeef5;
	border-bottom: 0;
	margin-bottom: 20px;

	.el-tag {
		margin-right: 10px;
	}

	.img_sku-item {
		display: inline-block;
		margin-right: 30px;
		vertical-align: middle;

		.img_sku-item__upload {
			position: relative;
			width: 94px;
			height: 94px;
			margin-top: 6px;
			padding: 4px;
			border: 1px solid #e5e5e5;
			border-radius: 4px;
			background-color: #fff;
			position: relative;
			margin-bottom: 10px;

			.arrow {
				position: absolute;
				width: 0;
				height: 0;
				top: -8px;
				left: 10%;
				border-style: solid;
				border-color: transparent;
				border-left: 5px solid transparent;
				border-right: 5px solid transparent;
				border-bottom: 5px solid #333;

				&::after {
					position: absolute;
					display: block;
					width: 0;
					height: 0;
					top: 0;
					margin-left: -10px;
					border-color: transparent transparent #fff;
					border-style: solid;
					border-width: 0 10px 10px;
					content: '';
				}
			}

			.el-image,
			.img-uploader,
			.uploader-icon {
				width: 84px;
				height: 84px;
			}

			.uploader-icon {
				line-height: 84px;
				font-size: 30px;
			}

			.el-image {
				display: block;
			}
		}
	}
}

.required_title::before {
	content: '*';
	color: #f56c6c;
}
</style>
